package com.liukaixin.product.ru.business.team.jointeamlist;

import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;

import com.liukaixin.product.ru.data.CallBackListener;
import com.liukaixin.product.ru.data.model.Team;
import com.liukaixin.product.ru.data.repositories.TeamsRepository;

import java.util.List;

import static com.google.common.base.Preconditions.checkNotNull;

/**
 * Created by liukaixin on 16/9/20.
 */

public class JoinTeamListPresenter
        implements JoinTeamListContract.Presenter {

    @NonNull
    private final TeamsRepository teamsRepository;

    @NonNull
    private final JoinTeamListContract.View joinTeamListView;

    @Nullable
    private Integer competitionId;

    private Handler handler = new Handler();

    public JoinTeamListPresenter(Integer competitionId, @NonNull TeamsRepository teamsRepository,
                                 @NonNull JoinTeamListContract.View joinTeamListView) {
        this.competitionId = competitionId;

        this.teamsRepository = checkNotNull(teamsRepository);
        this.joinTeamListView = checkNotNull(joinTeamListView);

        this.joinTeamListView.setPresenter(this);
    }

    @Override
    public void refresh() {
        handler.postDelayed(() -> {
            joinTeamListView.initPage();
            // 获取第一页的十条数据
            getTeamsByCompetitionId(1, 10, competitionId);
        }, 1000);
    }

    @Override
    public void loadMore(Integer page) {
        getTeamsByCompetitionId(page, 10, competitionId);
    }

    private void getTeamsByCompetitionId(final Integer page,
                                         final Integer rows,
                                         final Integer competitionId) {
        teamsRepository.getTeamsByCompetitionId(page, rows, competitionId,
                new CallBackListener<List<Team>>() {
                    @Override
                    public void onCompleted() {
                        // do nothing
                    }

                    @Override
                    public void onError(String msg) {
                        joinTeamListView.showError(msg);
                    }

                    @Override
                    public void onNext(List<Team> teams) {
                        showDataOnView(teams, page);
                    }
                });
    }

    private void showDataOnView(final List<Team> teams,
                                final Integer page) {
        handler.postDelayed(() -> {
            if (page == 1 && teams.isEmpty()) {
                joinTeamListView.showNoData();
                return;
            }
            if (page == 1) {
                joinTeamListView.clearAdapter();
            }
            if (teams.size() % 10 > 0
                    || (page != 1 && teams.isEmpty())) {
                joinTeamListView.setNoMoreData();
            }
            joinTeamListView.showData(teams);
        }, 1000);
    }
}
